import axios from "axios";
import { useAppStore } from "@/store/index";
import { navigateTo } from "@/router/index";
import { Toast } from 'vant'

const instance = axios.create({
    baseURL: 'https://h5.tonghuajiankang.com/prod-api',
    timeout: 60000,
});

// 请求拦截器
instance.interceptors.request.use(
    (config) => {
        // const store = useAppStore();
        // const token = store.token;
        let token = localStorage.getItem('token') || '';
        if (token) {
            config.headers = {
                "Authorization": token,
                ...config.headers
            }
        }
        const urlList = ['']
        const flag = urlList.some(v => config.url.indexOf(v) != -1)
        if (!flag) {
            store.setSpinning(true)
        }
        return config;
    },
    (error) => {
        // 处理请求错误
        const store = useAppStore();
        store.setSpinning(false)
        return Promise.reject(error);
    }
);

// 响应拦截器
instance.interceptors.response.use(
    (response) => {
        console.log('response: ', response);
        const store = useAppStore();
        store.setSpinning(false)
        if (response.data.code == '401') {
            store.logout()
        }

        if (response.data.success === false) {
            // message.error(response.data.message);
            return Promise.reject(response.data);
        }

        return response.data;
    },
    (error) => {
        const store = useAppStore();
        store.setSpinning(false)
        return Promise.reject(error);
    }
);

export default instance;